<template>
    <div>
        <el-card class="card" shadow="always">
            <el-row>
                <el-col :span="6" class="side">
                    <el-row>
                      <el-col :span="24">
                        <el-input
                            v-model="seach"
                            :suffix-icon="Search"
                            style="width: 95%;border: 3px solid #9cc8f3;border-radius: 6px;"
                        />
                        <el-card style="width: 95%;margin-top: 15px;">
                            <el-row >
                                <el-col :span="10" >
                                    <el-tag type="">
                                        <el-icon><User /></el-icon>
                                        总人数：{{users.length}}
                                    </el-tag>
                                </el-col>
                                <el-col :span="10" :offset="3">
                                    <el-tag type="success">
                                        <el-icon><Connection /></el-icon>
                                        在线人数：{{$store.state.chat.onlineUser.length }}
                                    </el-tag>
                                </el-col>
                            </el-row>
                        </el-card>
                        <div v-if="$store.state.chat.onlineUser.length > 0">
                            <el-card style="width: 95%;margin-top: 15px;"  v-for="user in $store.state.chat.onlineUser" :key="user.id">
                                <el-row class="onlineUser">
                                    <el-col :span="8" >
                                        <img :src="user.photo" style="width: 60px;height: 60px;border: 4px solid gray;">
                                    </el-col>
                                    <el-col :span="9" :offset="7">
                                        <el-tag type="" style="margin-bottom: 5px;">{{user.username}}</el-tag>
                                        <template v-if="badgeCount[user.id] == 1">
                                            <el-badge value="new" >
                                                <el-button type="warning" size="small" :icon="Position" @click="chat(user)">回复</el-button>
                                            </el-badge>
                                        </template>
                                        <template v-else>
                                            <el-button type="success" size="small" :icon="Position" @click="chat(user)">聊天</el-button>
                                        </template>
                                    </el-col>
                                </el-row>
                            </el-card>
                        </div>
                      </el-col>
                    </el-row>
                </el-col>
              <el-col :span="17" style="margin-left: 10px;">
                <el-row style="height: 70px;text-align: center;">
                  <el-col :span="24">
                    <span style="font-family:'Segoe UI';font-weight: bold;font-size:  20px;">{{title}}</span>
                    <svg t="1681196642653" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6688" width="48" height="48"><path d="M825.9584 641.2288H375.7568c-75.9296 0-137.472-61.5424-137.472-137.472V252.0064c0-75.9296 61.5424-137.472 137.472-137.472h450.2016c75.9296 0 137.472 61.5424 137.472 137.472v251.7504c0 75.9296-61.5424 137.472-137.472 137.472z" fill="#4BE2AC" p-id="6689"></path><path d="M681.0624 278.528H212.224c-81.5104 0-147.5584 66.048-147.5584 147.5584v252.7744c0 81.5104 66.048 147.5584 147.5584 147.5584h25.6512c8.7552 0 15.872 7.1168 15.872 15.872v56.1152c0 11.7248 12.3392 19.4048 22.8352 14.2336l172.4416-84.5824c2.1504-1.0752 4.5568-1.6384 7.0144-1.6384h225.0752c81.5104 0 147.5584-66.048 147.5584-147.5584V426.0864c-0.0512-81.5104-66.0992-147.5584-147.6096-147.5584z" fill="#4BE2AC" p-id="6690"></path><path d="M672.6144 278.528H242.176l-3.84 3.84v200.6528c0 87.3472 70.8096 158.208 158.208 158.208h408.7296c7.936 0 15.7696-0.6144 23.3984-1.7408V434.5856c-0.0512-86.2208-69.888-156.0576-156.0576-156.0576z" fill="#06CC76" p-id="6691"></path><path d="M280.4224 565.3504m-47.9744 0a47.9744 47.9744 0 1 0 95.9488 0 47.9744 47.9744 0 1 0-95.9488 0Z" fill="#FFFFFF" p-id="6692"></path><path d="M438.8864 565.3504m-47.9744 0a47.9744 47.9744 0 1 0 95.9488 0 47.9744 47.9744 0 1 0-95.9488 0Z" fill="#FFFFFF" p-id="6693"></path><path d="M598.1184 565.3504m-47.9744 0a47.9744 47.9744 0 1 0 95.9488 0 47.9744 47.9744 0 1 0-95.9488 0Z" fill="#FFFFFF" p-id="6694"></path></svg>
                  </el-col>
                </el-row>
                <el-row style="height: 360px;">
                  <el-col :span="24">
                    <div v-for="(m,index) in $store.state.chat.chatMessages" :key="index">
                        <el-row style="margin-bottom: 5px" v-if="m.userId == $store.state.user.id">
                            <el-col :span="21" style="text-align: right;" >
                                <el-button type="primary"> {{m.text}}</el-button>
                            </el-col>
                            <el-col :span="2">
                                <img :src="$store.state.user.photo" style="width: 40px; height: 40px;border-radius: 50%;margin-left: 10px;border: 2px solid rgb(138, 76, 76);">
                            </el-col>
                        </el-row>
                        <el-row style="margin-bottom: 5px" v-else>
                            <el-col :span="2">
                                <img :src="$store.state.chat.chatUserPhoto" style="width: 40px; height: 40px;border-radius: 50%;border: 2px solid rgb(138, 76, 76);">
                            </el-col>
                            <el-col :span="21" style="text-align: left;margin-right: 3px;">
                                <el-button type="success"> {{m.text}}</el-button>
                            </el-col>
                        </el-row>
                    </div>
                  </el-col>
                </el-row>
                <el-divider></el-divider>
                <el-row>
                    <el-col :span="24">
                        <el-input v-model="message" placeholder="请输入要发送的消息！" style="width: 90%;margin-right: 10px;"></el-input>
                        <el-button type="primary" :icon="Promotion" @click="MessageTest" ></el-button>
                    </el-col>
                </el-row>
              </el-col>
            </el-row>
        </el-card>
    </div>
</template>
<script>
    import {ref,onMounted,onUnmounted,reactive} from 'vue';
    import {ElMessage} from 'element-plus';
    import {useStore} from 'vuex';
    import {Search,Position,Promotion} from '@element-plus/icons-vue'
    import request from '@/utils/request'
    export default{
        name:'GroupChat',
        setup() {
            const icon = {Search,Position,Promotion}
            let message = ref('');
            let title = ref('聊天窗口');
            let seach = ref('')
            const store = useStore();
            let badgeCount = ref([])
            let users = ref([])
            const socketUrl = `ws://localhost:3030/websocket/${store.state.user.token}/`;
            let socket = null;
            let getUserAll = () => {
                request({
                    url:'user/get/all/',
                    method:'get',
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    },
                }).then((resp) => {
                    users.value = resp;
                }).catch(() => {
                });
            }
            getUserAll()
            onMounted(() => {
                socket = new WebSocket(socketUrl);
                store.commit('UpdateSocket',socket)
                socket.onopen = () => {
                    console.log('已建立连接！');
                }
                //接收服务端传过来的消息
                socket.onmessage = message => {
                    const data = JSON.parse(message.data)
                    if(data.onlineUser){
                        let onlineUsers = reactive([]);
                        for (const user of data.onlineUser) {
                            if(user.id != parseInt(store.state.user.id)){
                                onlineUsers.push(user)
                            }
                        }
                        store.commit('UpdateOnlineUser',onlineUsers)
                    }
                    if(data.text && data.from){
                        //接收的消息不为null，从sessionStorage读取聊天记录
                        let chatMessages =JSON.parse(sessionStorage.getItem(store.state.user.id+"@"+data.from))
                        if(chatMessages){
                            chatMessages.push({text:data.text,userId:data.from})
                            sessionStorage.setItem(store.state.user.id+"@"+data.from,JSON.stringify(chatMessages))
                            if(data.from === store.state.chat.chatUserId){
                                store.commit('UpdateChatMessages',chatMessages)
                            }
                        }else{
                            /*
                            注意：
                                如果发送信息的用户不是正在聊天的用户
                                就先直接存入sessionStorage，就不添加到当前聊天窗口
                                保证切换聊天窗口时，记录还在
                            */
                            if(data.from === store.state.chat.chatUserId){
                                store.commit('AddChatMessage',{
                                    text:data.text,
                                    userId:data.from
                                })
                            }
                            let chatMessages = [];
                            chatMessages.push({text:data.text,userId:data.from})
                            badgeCount.value[parseInt(data.from)] = 1;
                            sessionStorage.setItem(store.state.user.id+"@"+data.from,JSON.stringify(chatMessages))
                        }
                    }
                    if(data.user){
                        ElMessage({
                            message: data.user.username + '下线!',
                            grouping: true,
                            type: 'warning',
                        })
                        sessionStorage.removeItem(store.state.user.id+"@"+data.user.id)
                        if(store.state.chat.chatUserId === data.user.id){
                            let chatMessages = [];
                            store.commit('UpdateChatMessages',chatMessages)
                        }
                        title.value = "聊天窗口"
                    }
                    if(data.online){
                        ElMessage({
                            message: data.online.username + '上线!',
                            grouping: true,
                            type: 'success',
                        })
                    }
                }
                socket.onclose = () => {
                    console.log('已断开连接')
                }
            })
            onUnmounted(() => {
                socket.close();
            })
            const chat = function(user){
                title.value = "正在和"+user.username+"聊天"
                store.commit('UpdateChatUser',user.id)
                store.commit('UpdateChatUserPhoto',user.photo)
                // 现在sessionStorage中获取聊天记录
                let chatMessages =JSON.parse(sessionStorage.getItem(store.state.user.id+"@"+user.id));
                if(chatMessages){
                    store.commit('UpdateChatMessages',chatMessages)
                }else{//没有聊天记录，就清空当前聊天窗口
                    chatMessages = [];
                    store.commit('UpdateChatMessages',chatMessages)
                }
                badgeCount.value[user.id]= 0;
            }
            const MessageTest = function(){
                let chatUserId = store.state.chat.chatUserId;
                if(!message.value){
                    ElMessage({
                            message: '发送的信息为空!',
                            grouping: true,
                            type: 'warning',
                    })
                }else{
                    if(chatUserId === '' || !chatUserId){
                        ElMessage({
                                message: '请选择聊天好友!',
                                grouping: true,
                                type: 'warning',
                        })
                    }else{
                        // 先在sessionStorage中取出聊天记录，然后与新发送的信息进行拼接，再更新
                        let chatMessages = JSON.parse(sessionStorage.getItem(store.state.user.id+"@"+chatUserId))
                        if(chatMessages){
                            chatMessages.push({text:message.value,userId:store.state.user.id})
                            sessionStorage.setItem(store.state.user.id+"@"+chatUserId, JSON.stringify(chatMessages))
                            store.commit('UpdateChatMessages',chatMessages)
                        }else{
                            store.commit('AddChatMessage',{
                                text:message.value,
                                userId:store.state.user.id
                            })
                            let chatMessages = [];
                            chatMessages.push({text:message.value,userId:store.state.user.id})
                            sessionStorage.setItem(store.state.user.id+"@"+chatUserId,JSON.stringify(chatMessages))
                        }
                        store.state.chat.socket.send(JSON.stringify({
                            from:store.state.user.id,
                            text:message.value,
                            to:store.state.chat.chatUserId
                        })) 
                    }
                }
            }
            return {
                seach,
                users,
                ...icon,
                title,
                message,
                MessageTest,
                chat,
                badgeCount
            }
        },
    }
</script>
<style scoped> 
.card{
    margin: 10px auto;
    width: 70vw;
    height: 75vh;
}
.side{
    height: 70vh;
    box-sizing: border-box;
    border-right: 5px solid rgb(198, 195, 195);
}
.onlineUser{
    cursor: pointer;
}
.onlineUser:hover{
    opacity: 0.4;
}
</style>